<?php
class EWebby_ModuleLoader {
	public static function getModulesFrom($application) {
		$modules = array();
		
		$directory = $application->handlersDirectory;
		$fdirectory = APP_PATH . $directory;
		if (($handle = opendir($fdirectory)) != null) {
		    while ( ($file = readdir($handle)) !== false ) {
		        if ( $file != '.'
		        	&& $file != '..' )  {
		        	$directoryPath = $fdirectory . DIRECTORY_SEPARATOR . $file;
		        	if( is_dir($directoryPath) ) { 
		            	$moduleInstance = self::_getModuleInstance($directory . '_' . $file . '_WebModule');
		            	if( $moduleInstance != null ) {
		            		$moduleInstance->application = $application;
		            		$modules[ $moduleInstance->getName() ] = $moduleInstance;
		            	}
		        	}
		        }
		    }
		    closedir($handle);
		}
		
		return $modules;
	}
	
	private static function _getModuleInstance($className) {
		try {
			if( EWebby_Runtime_Importer::Import($className) 
				&& class_exists($className, false)) {
				return new $className();
			}
		} catch (EWebby_Runtime_Exception $ex) { }
		
		return null;
	}
}